import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { PersonInfoService } from 'src/app/services/project/smart-site/person-info';
import { Router } from '@angular/router';
import { TeamModal, MajorModal } from './category.model';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { consoleTestResultHandler } from 'tslint/lib/test';

@Component({
  selector: 'app-categories',
  templateUrl: './categories.component.html',
  styleUrls: ['./categories.component.scss']
})
export class CategoriesComponent implements OnInit {
  public projectInfo: any = JSON.parse(window.localStorage.getItem('project'));

  public managerPageInfo = {
    nzPageIndex: 1,
    maxResultCount: 27,
    nzTotal: 0
  };
  public rosterPageInfo = {
    nzPageIndex: 1,
    maxResultCount: 10,
    nzTotal: 0
  };


  // 班组
  public showTeam = true;
  public banzuList = [];
  public teamModal = new TeamModal();
  public banzuLeaderList = [];
  public isTeamVisible = false; // 班组新增编辑弹窗
  public currentLeader = null;
  // 工种
  public gongzhongList = [];
  public majorModal = new MajorModal();
  public ismajorVisible = false; // 工种新增编辑弹窗

  public isDelete = false; // 删除提示框
  public tableHeight = {
    y: (window.innerHeight * 0.65) + 'px'
  };

  constructor(
    private router: Router,
    private personInfoService: PersonInfoService,
    public message: NzMessageService,
    public mzModal: NzModalService,
  ) { }


  // tabs 改变事件
  selectTabChange(e) {
    console.log(e);
    if (e.index === 0) {
      this.showTeam = true;
    } else {
      this.showTeam = false;
    }
  }


  // 查询班组列表
  async handleQueryTeamList(params) {
    params = Object.assign(params, {
      maxResultCount: this.managerPageInfo.maxResultCount,
      code: this.projectInfo.code,
    });
    const res = await this.personInfoService.QueryTeamsPagedList(params);
    this.banzuList = res.result.items;
    this.managerPageInfo.nzTotal = res.result.totalCount;


  }


  // 新增或编辑 班组 type 1: 新增 else：编辑
  addTeam(type) {
    console.log(type);
    this.isTeamVisible = true;
    if (type === 1) {
      this.teamModal = new TeamModal(); // 新建时初始化表单
      this.currentLeader = null; // 初始化选中项
    } else {
      this.teamModal = new TeamModal(type);
      this.currentLeader = { label: type.manageName, value: type.manageId };
    }

  }
  // 确定新增班组
  async handleTeamOk() {

    this.teamModal.manageId = this.currentLeader['value'];
    console.log(this.teamModal);
    const res = await this.personInfoService.CreateOrModifyTeam(this.teamModal);
    if (res.success) {
      this.message.success('操作成功');
      this.isTeamVisible = false;
      this.teamModal = new TeamModal(); // 新建时初始化表单
      this.handleQueryTeamList({
        skipCount: 0,
      });
    }
  }





  // 选择框改变事件
  selChange(value: { label: string; value: any; }): void {
    // console.log(value);
  }
  // 绑定 输入框
  compareFn = (o1: any, o2: any) => (o1 && o2 ? o1.value === o2.value : o1 === o2);

  // 查询负责人选项
  async handleQueryLeaderList() {
    const leaderParams = {
      code: this.projectInfo.code,
      maxResultCount: 1000,
      type: 2,
    };
    this.personInfoService.QueryProjectUsersPagedList(leaderParams).then((res) => {
      if (res.success) {

        const Temp = res.result.items;
        const tempOrg = [];
        Temp.forEach(element => {
          tempOrg.push({ label: element.name, value: element.userId });
        });
        this.banzuLeaderList = tempOrg;
      } else {
        // this.message.warning(res.error.message);
      }
    });
  }

  // 查询工种列表
  async handleQueryRosterList(params) {
    params = Object.assign(params, {
      maxResultCount: this.rosterPageInfo.maxResultCount,
    });

    const res = await this.personInfoService.QueryMajorsPagedList(params);
    this.gongzhongList = res.result.items;
    this.rosterPageInfo.nzTotal = res.result.totalCount;
  }


  // 新增或编辑工种
  async addMajor(type) {
    this.ismajorVisible = true;
    if (type === 1) {
      this.majorModal = new MajorModal();
    } else {
      this.majorModal = new MajorModal(type);
    }

  }

  // 确认保存或编辑工种
  async handleMajorOk() {
    this.isTeamVisible = false;
    console.log(this.majorModal);
    const res = await this.personInfoService.CreateOrModifyMajor(this.majorModal);
    if (res.success) {
      this.message.success('操作成功');
      this.ismajorVisible = false;
      this.majorModal = new MajorModal();
      this.handleQueryRosterList({
        skipCount: 0,
      });
    }
  }



  // 执行删除班组或工种 type = 1 删除班组
  async deleteTeamOrMajor(data, type?) {
    console.log(data);
    console.log(type);
    this.mzModal.error({
      nzTitle: '删除？',
      nzContent: `<b>确认要删除${data.name}吗？</b>`,
      nzOkText: '确定',
      nzCancelText: '取消',
      nzOkType: 'danger',
      nzOnOk: () => {
        if (type === 1) {
          this.personInfoService.RemoveTeam({ id: data.id }).then((res) => {
            if (res.success) {
              this.message.success('删除成功');
              this.handleQueryTeamList({
                skipCount: 0,
              });
            }
          });
        } else {
          this.personInfoService.RemoveMajor({ id: data.id }).then((res) => {
            if (res.success) {
              this.message.success('删除成功');
              this.handleQueryRosterList({
                skipCount: 0,
              });
            }
          });
        }


      },
      // nzOnCancel: () => this.isDelete = false
    });
  }

  // 班组页码切换
  async managerPageChange(index) {
    const data = {
      skipCount: index - 1,
    };
    await this.handleQueryTeamList(data);
  }
  // 工种页码切换
  async rosterPageChange(index) {
    const data = {
      skipCount: index - 1,
    };
    await this.handleQueryRosterList(data);
  }





  // 面包屑跳转

  routeToSurvey() {
    const projectId = JSON.parse(window.localStorage.getItem('project')).id;
    this.router.navigate([`/inner/project/${projectId}/survey`], { queryParams: { info: 'project' } });
  }

  async rosterPageSizeChange(size) {
    this.rosterPageInfo.maxResultCount = size;
    const data = {
      skipCount: 0,
    };
    await this.handleQueryRosterList(data);
  }




  // 初始化
  initData() {
    const data = {
      skipCount: 0,
    };
    this.handleQueryTeamList(data);
    this.handleQueryLeaderList();
    this.handleQueryRosterList(data);
  }

  ngOnInit() {
    this.initData();
  }

}
